<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/3
 * Time: 10:32:33
 */

namespace Service\CommodityService;

use _PHPStan_b8e553790\Nette\Neon\Exception;
use Service\Code\Normal;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsBrand;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\MnStoreGoods;
use Service\EsService\EsPublishMsgService;
use Service\BaseService;
/**
 * 自建商品服务
 */
class SelfGoodsService extends BaseService
{
    public function makeWhere($param){
        $where = [
            ['ly_goods.df','=',0],
            ['ly_goods.cid','=',$param['cid']],
            ['ly_goods.is_fast_delivery','<>',1],
            ['ly_goods.is_trade','=',1],
        ];

        if(isset($param['word']) && $param['word']){
            $where[] = ['ly_goods.skucode|ly_goods.barcode|ly_goods.name|ly_goods.origin','like',"%{$param['word']}%"];
        }

        if (isset($param['class_id']) && $param['class_id']) {
            $class_ids   = Goodsclass::instance()->where('pid', $param['class_id'])->pluck('id')->toArray();
            $class_ids[] = $param['class_id'];
            $where[] = [function($query) use ($class_ids){
                $query->whereIn('ly_goods.class_id',$class_ids);
            }];
        }

        if(isset($param['brand_id']) && $param['brand_id']){
            $where[] = ['ly_goods.brand_id','=',$param['brand_id']];
        }

        if(isset($param['is_bonded'])){
            $where[] = ['ly_goods.is_bonded','=',$param['is_bonded']];
        }

        if(isset($param['manager_tag']) && $param['manager_tag']){
            $where[] = ['ly_goods.manager_tag','=',$param['manager_tag']];
        }

        if(isset($param['goods_status'])){
            $where[] = ['ly_goods.status','=',$param['goods_status']];
        }

/*        if(isset($param['transit_template'])){
            $where[] = ['ly_goods.transit_template','=',$param['transit_template']];
        }*/

        if(isset($param['price_type']) && (isset($param['price_start']) || isset($param['price_end']))){
            switch ($param['price_type']){
                case 1:
                    $string = "ly_goods.price_cost";
                    break;
                case 2:
                    $string = "ly_goods.price_store";
                    break;
                case 3:
                    $string = "ly_goods.price_recommend";
                    break;
                case 4:
                    $string = "ly_goods.price_recommend_vip";
                    break;
                default: $string = 'ly_goods.price_cost';
            }
            if(!empty($param['price_start'])){
                $where[] = [$string,'>=',$param['price_start']];
            }
            if(!empty($param['price_end'])){
                $where[] = [$string,'<=',$param['price_end']];
            }
        }

        if(isset($param['transit_template'])){
            $transit_template = $param['transit_template'];
            $where[] = [function($query) use ($transit_template){
                $query->whereIn('ly_goods.template_id',$transit_template);
            }];
        }

        if(isset($param['num_storage_status'])){
            if($param['num_storage_status'] == 1){
                $where[] = ['ly_goods.num_storage','>',0];
            }else{
                $where[] = ['ly_goods.num_storage','=',0];
            }
        }
        if(isset($param['goods_info_wrong'])){
            if($param['goods_info_wrong'] == 1){ //商品资料异常，结算价低于成本价时，未设置价格，未选择分类
                $where[] = [function($query){
                    $query->where('ly_goods.price_store','<','price_cost')
                       ->orWhereRaw('ly_goods.price_store=0 or class_id=0');
                }];
            }else{
                $where[] = [function($query){
                    $query->where('ly_goods.price_store','>=','price_cost')
                        ->orWhereRaw('ly_goods.price_store>0 or class_id>0');
                }];
            }
        }

        return $where;
    }
    /**
     * 自建商品列表
     * @param $param
     * @return array
     */
    public function goodsList($param){
        $limit = $param['limit'] ?? 10;
        $page = $param['page'] ?? 1;

        $where = $this->makeWhere($param);
        /*$fields = ['id','name','skucode','barcode','img','price_market','price_cost','price_store','price_recommend','price_recommend_vip','num_storage','num_sale','month_sale','is_bonded','origin','weight','supply_class_id','status','cd'];*/
        $data_list = Goods::instance()
            ->where($where)
            ->orderByRaw('up desc,show_order desc,id desc')
            ->paginate($limit, ['*'], 'page', $page);
        $total = $data_list->total();
        $list = $data_list->items();
        foreach ($list as &$v){
            $v['class_name']   = GoodsClass::instance()->where(['id' => $v['class_id']])->value('name');
            $v['brand_name']   = GoodsBrand::instance()->where(['id' => $v['brand_id']])->value('name');
            $v['except_money'] = round(($v['price_store'] - $v['price_cost']), 2);
            if($v['cd']){
                $v['cd'] = date('Y-m-d H:i:s',$v['cd']);
            }

        }
        return Normal::returnCode(Normal::SUC,'成功',['list'=>$list,'total'=>$total]);
    }

    public function changeGoodsStatus($param){
        ini_set('memory_limit','-1');
        $status = $param['status'];
        if(!isset($param['goods_ids']) || !$param['goods_ids']){
            return Normal::returnCode(Normal::FAIL,'请选择商品');
        }

        $goods_list = Goods::instance()
            ->where(['cid'=>$param['cid'],'df'=>0,'is_trade'=>1])
            ->where('is_fast_delivery','<>',1)
            ->whereIn('id',$param['goods_ids'])
            ->get()->toArray();

        Db::beginTransaction();
        try{
            $goods_ids = array_column($goods_list,'id');
            Goods::instance()
                ->whereIn('id',$goods_ids)
                ->update(['status'=>$status]);
            $mn_user = Mnuser::instance()->lists(['pid'=>$param['cid'],'auto_up'=>1,'_fields_'=>'id,mid,type,supplier_id,goods_source,sid']);
            $mn_user_ids = array_column($mn_user,'id');
            if($status == 1){ //商品上架
                $updateData = [];
                $insertData = [];
                foreach ($goods_list as $gv){
                    foreach ($mn_user as $mk){
                        $store_has_goods = MnStoreGoods::instance()->info(['mn_sid'=>$mk['id'],'goods_id'=>$gv['id']]);
                        $item['sid']       = $param['sid'];
                        $item['mn_sid']    = $mk['id'];
                        $item['mid']       = $mk['mid'];
                        $item['goods_id']  = $gv['id'];
                        $item['status']    = 1;
                        $item['df']        = 0;
                        $item['type']      = 2;
                        $item['cd']        = time();
                        $item['md']        = time();
                        $item['price']     = $gv['price_recommend'];
                        $item['price_vip'] = $gv['price_recommend_vip'];
                        if($store_has_goods){ //店铺已有此商品
                            $updateData[]      = $item;
                        }else{
                            $insertData[]      = $item;
                        }
                    }
                }
                if(!empty($insertData)){
                    MnStoreGoods::instance()->insert($insertData);
                }
                if(!empty($updateData)){
                    MnStoreGoods::instance()->insert($updateData);
                }

            }else{ //批量下架商品
                MnStoreGoods::instance()->whereIn('mn_sid',$mn_user_ids)->whereIn('goods_ids',$goods_ids)->update(['status'=>0]);
            }

            //更新ES
            $goods_ids_list = array_column($goods_list,null,'id');
            $storeGoodsList = MnStoreGoods::instance()->whereIn('mn_sid',$mn_user_ids)->whereIn('goods_ids',$goods_ids)
                ->get()->toArray();
            $insertEsData = [];
            foreach ($storeGoodsList as $values){
                $insertItem['id']                   = $values['id'];
                $insertItem['goodsId']              = $values['goods_id'];
                $insertItem['name']                 = $goods_ids_list[$values['goods_id']]['name'] ?? '';
                $insertItem['classifyID']           = $goods_ids_list[$values['goods_id']]['class_id'] ?? '';
                $insertItem['storeID']              = $values['mn_sid'];
                $brand_id                           = $goods_ids_list[$values['goods_id']]['brand_id'] ?? '';
                $insertItem['brandName']            = GoodsBrand::instance()->info(['id' => $brand_id])['name'] ?? '';
                $insertItem['isTrade']              = $goods_ids_list[$values['goods_id']]['is_trade'] ?? '';
                $insertItem['channelID']            = $param['cid'];
                if($status == 1){ //批量上架商品
                    $insertItem['isChannelGoodsActive'] = true;
                    $insertItem['isStoreGoodsActive']   = $goods_ids_list[$values['goods_id']]['status'] > 0;
                }else{ //批量下架商品
                    $insertItem['isChannelGoodsActive'] = false;
                    $insertItem['isStoreGoodsActive']   = false;
                }

                $insertEsData[]                     = $insertItem;
            }
            if(!empty($insertEsData)){
                $res = EsPublishMsgService::instance()->storeESMessageProducer($insertEsData);
                if($res['code'] != Normal::SUC){
                    throw new Exception('更新ES失败'.$res['msg']);
                }
            }
            Db::commit();
        }catch (\Throwable $e){
            Db::rollBack();
            return Normal::returnCode(Normal::FAIL,'失败'.$e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'成功');
    }

    /**
     * 新增自建商品
     * @param $param
     * @return array
     */
    public function add($param) {
        $result = $this->validate($param);
        if($result['code'] != Normal::SUC){
            return Normal::returnCode(Normal::FAIL,$result['msg']);
        }
        $checkSup = Goods::instance()
            ->where(['barcode'=>$param['barcode'],'is_bonded'=>$param['is_bonded'],'cid'=>$param['cid'],'is_trade'=>1,'df'=>0])->exists();
        if(!$checkSup){
            return Normal::returnCode(Normal::FAIL,'同类型商品已存在');
        }
        if($param['weight']){
            $param['weight'] = $param['weight'] * 1000;
        }
        $time = time();
        $param['skucode'] = 'zj'.$time.'m'.$param['manager_id'].'n0';

        Db::beginTransaction();
        try{
            Goods::instance()
                ->insert([
                    'sid' => $param['sid'],
                    'cid' => $param['cid'],
                    'name' => $param['name'],
                    'skucode' => $param['skucode'],
                    'barcode' => $param['barcode'],
                    'is_bonded' => $param['is_bonded'],
                    'brand_id' => $param['brand_id'],
                    'class_id' => $param['class_id'],
                    'type' => $param['type'],
                    'num_storage' => $param['num_storage'],
                    'template_id' => $param['template_id'],
                    'weight' => $param['weight'],
                    'cd' => time(),
                    'md' => time(),
                ]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollBack();
            return Normal::returnCode(Normal::FAIL,'新增失败：'.$e->getMessage());
        }

        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    public function validate($param){
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'商品名称不能为空');
        }
        if(!isset($param['barcode']) || !$param['barcode']){
            return Normal::returnCode(Normal::FAIL,'国际条码不能为空');
        }
        if(!isset($param['is_bonded']) || $param['is_bonded'] == ''){
            return Normal::returnCode(Normal::FAIL,'请选择商品类型');
        }
        if(!isset($param['brand_id']) || !$param['brand_id']){
            return Normal::returnCode(Normal::FAIL,'请选择品牌');
        }
        if(!isset($param['class_id']) || !$param['class_id']){
            return Normal::returnCode(Normal::FAIL,'请选择分类');
        }
        if(!isset($param['type'])){
            return Normal::returnCode(Normal::FAIL,'请设置定价方式');
        }
        if(!isset($param['num_storage']) || !is_numeric($param['num_storage'])){
            return Normal::returnCode(Normal::FAIL,'请设置可售库存');
        }
        if(!isset($param['template_id']) || !$param['template_id']){
            return Normal::returnCode(Normal::FAIL,'请选择运费模板');
        }
        return Normal::returnCode(Normal::SUC,'验证成功');
    }
}